<script setup lang="js">
import { ref,onMounted,watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import {getCoupon,updateCoupon,createCoupon} from "@/api/coupon.js";
import {ElMessage, ElMessageBox} from "element-plus";
const route = useRoute();
const router = useRouter();

const defaultCoupon = {
  type: 0,
  name: null,
  platform: 0,
  amount: null,
  perLimit: 1,
  minPoint: null,
  startTime: null,
  endTime: null,
  useType: 0,
  note: null,
  publishCount: null,
  productRelationList: [],
  productCategoryRelationList: []
};
const defaultTypeOptions = [
  {
    label: '全场赠券',
    value: 0
  },
  {
    label: '会员赠券',
    value: 1
  },
  {
    label: '购物赠券',
    value: 2
  },
  {
    label: '注册赠券',
    value: 3
  }
];
const defaultPlatformOptions = [
  {
    label: '全平台',
    value: 0
  },
  {
    label: '移动平台',
    value: 1
  },
  {
    label: 'PC平台',
    value: 2
  }
];



onMounted(() => {
  if(route.query.id) {
    getCoupon(route.query.id).then(res => {
      couponFormList.value = res.data.data;
    });
  } else {
    couponFormList.value = defaultCoupon;
  }
});

const coupon = Object.assign({}, defaultCoupon);
const typeOptions = Object.assign({}, defaultTypeOptions);
const platformOptions = Object.assign({}, defaultPlatformOptions);


// 表单数据
const couponFormList = ref({});
const couponFrom = ref(null);
const selectProduct = ref(null);
const selectProductLoading = ref(false);
const selectProductOptions = ref([]);
const selectProductCate = ref(null);
const productCateOptions = ref([]);

// 表单规则
const rules = {
  name: [
    {required: true, message: '请输入优惠券名称', trigger: 'blur'},
    {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
  ],
  publishCount: [
    {required: true, message: '只能输入整数', trigger: 'blur'}
  ],
  amount: [
    {required: true, message: '只能输入整数',trigger: 'blur'}
  ],
  minPoint: [
    {required: true,message: '只能输入整数',trigger: 'blur'}
  ]
}

// 提交表单
const onSubmit = (formName) => {
  couponFrom.value.validate((valid) => {
    if (valid) {
     ElMessageBox.confirm('是否提交数据？', '提示:', {
       confirmButtonText: '确定',
       cancelButtonText: '取消',
       type: 'warning'
     }).then(() => {
       if(route.query.id) {
         updateCoupon(route.query.id, couponFormList.value).then(res => {
           ElMessage.warning(res.data.message);
           ElMessage.success('修改成功');
           router.push({name: 'CouponManagement'});
         });
       } else {
         // 新增数据
         createCoupon(couponFormList.value).then(res => {
           ElMessage.warning(res.data.message);
           ElMessage.success('新增成功');
           router.push({name: 'CouponManagement'});
         });
       }
     })
    } else {
      ElMessage.error('请检查输入项');
      return false;
    }
  })
}


// 重置表单
const resetForm = () => {
  couponFormList.value = '';
}

// 指定分类---删除按钮
const handleDeleteProductCateRelation = (index) => {
  couponFormList.value.productCategoryRelationList.splice(index, 1);
}

// 指定商品---删除按钮
const handleDeleteProductRelation = (index) => {
  couponFormList.value.productRelationList.splice(index, 1);
}

// 监听listQuery变化，同步到checkForm
watch(() =>coupon, (newVal) => {
        couponFormList.value = newVal
    },
    {immediate: true}
)
</script>

<template>
  <div class="coupon-detail">
    <el-card style="width: 800px;">
      <el-form :model="couponFormList" :rules="rules"  ref="couponFrom" label-width="150px" label-position="right">
        <el-form-item label="优惠券类型：">
          <el-select v-model="couponFormList.type" clearable placeholder="请选择优惠券类型" class="input-width">
            <el-option
                v-for="type in typeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券名称：" prop="name">
          <el-input v-model="couponFormList.name" clearable placeholder="请输入优惠券名称" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="适用平台：">
          <el-select v-model="couponFormList.platform" clearable placeholder="请选择适用平台" class="input-width">
            <el-option
                v-for="platform in platformOptions"
                :key="platform.value"
                :label="platform.label"
                :value="platform.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总发行量：" prop="publishCount">
          <el-input type="number" v-model="couponFormList.publishCount" clearable placeholder="只能输入正整数" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="面值大小：" prop="amount">
          <el-input type="number" v-model="couponFormList.amount" clearable placeholder="请输入面值金额大小" class="input-width">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领：">
          <el-input type="number" v-model="couponFormList.perLimit" clearable placeholder="请输入每人限领" class="input-width">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用门槛：" prop="minPoint">
          <el-input type="number" v-model="couponFormList.minPoint" placeholder="只能输入正整数" class="input-width">
            <template #prepend>满</template>
            <template #append>元可用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="领取日期：" prop="enableTime">
            <el-date-picker
                v-model="couponFormList.enableTime"
                type="date"
                format="YYYY-MM-DD"
                date-format="MMM DD, YYYY"
                placeholder="请选择时间"
                clearable
                style="width: 400px"
            >
            </el-date-picker>
       </el-form-item>
        <el-form-item label="有效日期：">
          <el-date-picker
              v-model="couponFormList.startTime"
              type="date"
              format="YYYY-MM-DD"
              date-format="MMM DD, YYYY"
              placeholder="请选择开始日期"
              clearable
              style="width: 180px; margin-right: 10px"
          >
          </el-date-picker>
           至
          <el-date-picker
              v-model="couponFormList.endTime"
              type="date"
              format="YYYY-MM-DD"
              date-format="MMM DD, YYYY"
              placeholder="请选择结束日期"
              clearable
              style="width: 180px; margin-left: 10px"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="可使用商品：">
          <el-radio-group v-model="couponFormList.useType">
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
            <el-radio-button :label="2">指定商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="couponFormList.useType===1">
          <el-cascader
              clearable
              placeholder="请选择分类名称"
              v-model="selectProductCate"
              :options="productCateOptions"
              style="width: 200px"
          >
          </el-cascader>
          <el-button style="margin-left: 10px" @click="handleAddProductCategoryRelation()">添加</el-button>
          <el-table ref="productCateRelationTable"
                    :data="couponFormList.productCategoryRelationList"
                    style="width: 100%;margin-top: 20px"
                    border>
            <el-table-column label="分类名称" align="center">
              <template #default="{row}">{{row.parentCategoryName}}>{{row.productCategoryName}}</template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{row}">
                <el-button size="mini"
                           type="text"
                           @click="handleDeleteProductCateRelation(index, row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-show="couponFormList.useType===2">
          <el-select
              v-model="selectProduct"
              filterable
              remote
              reserve-keyword
              placeholder="商品名称/商品货号"
              :remote-method="searchProductMethod"
              :loading="selectProductLoading"
              style="width: 200px"
          >
            <el-option
                v-for="item in selectProductOptions"
                :key="item.productId"
                :label="item.productName"
                :value="item.productId">
              <span style="float: left">{{ item.productName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.productSn }}</span>
            </el-option>
          </el-select>
          <el-button style="margin-left: 10px" @click="handleAddProductRelation()">添加</el-button>
          <el-table ref="productRelationTable"
                    :data="couponFormList.productRelationList"
                    style="width: 100%;margin-top: 20px"
                    border>
            <el-table-column label="商品名称" align="center">
              <template #default="{row}">{{row.productName}}</template>
            </el-table-column>
            <el-table-column label="货号" align="center">
              <template #default="{row}">NO.{{row.productSn}}</template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{row}">
                <el-button size="mini"
                           type="text"
                           @click="handleDeleteProductRelation(index, row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注说明：">
          <el-input
              class="input-width"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="couponFormList.note">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('couponFrom')">提交</el-button>
          <el-button v-if="!route.query.id" @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="css">
.coupon-detail {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
}

.input-width{
  width: 400px;
}
</style>